<template>
<div class="app-container">
  <div v-if="device === 'desktop'" class="mb20">
    <el-button v-if="nodePower.includes('add')" type="success" icon="el-icon-plus" @click="show = true">{{ $t("common.add") }}</el-button>
    <el-button v-if="nodePower.includes('del')" type="danger" icon="el-icon-delete" :disabled="!!!delIds.length" @click="del">{{ $t("common.deletes") }}</el-button>
    <el-popover class="mlr10" placement="bottom" trigger="click">
      <ProForm ref="searchForm" :config="SFC" />
      <el-button type="primary" @click="onSearch('Goods')">{{
          $t("common.confirm")
        }}</el-button>
      <el-button slot="reference" type="primary" icon="el-icon-search">{{
          $t("common.search")
        }}</el-button>
    </el-popover>
    <el-button type="primary" icon="el-icon-refresh" plain @click="reset('searchForm', 'Goods')" />
  </div>
  <div v-else class="mb20">
    <el-button v-if="nodePower.includes('add')" type="success" icon="el-icon-plus" @click="show = true" />
    <el-button v-if="nodePower.includes('del')" type="danger" icon="el-icon-delete" :disabled="!!!delIds.length" @click="del" />
    <el-popover class="mlr10" placement="bottom" trigger="click">
      <ProForm ref="searchForm" :config="SFC" />
      <el-button type="primary" @click="onSearch('Goods')">{{
          $t("common.confirm")
        }}</el-button>
      <el-button slot="reference" type="primary" icon="el-icon-search" />
    </el-popover>
    <el-button type="primary" icon="el-icon-refresh" plain @click="reset('searchForm', 'Goods')" />
  </div>

  <!--  -->
  <ProTable index selection border :table-row-class-name="tableRowClassName" :is-loading="isLoading" :data="list" :page="page" :column="column" :row-control="['view', 'spec', 'edit', 'del']" @row-control-click="onRcc" @page-change="onPageChange('Goods', $event)" @selection-change="delIds = $event.map(({ product_id }) => product_id)">
    <template #product_id="{ row }">{{
        $t(row.product_id)
      }}</template>
    <template #product_status="{ row }">{{
        $t(goodsStatus[row.product_status])
      }}</template>
    <template #product_img="{ row }">
      <ProImage :src="row.product_img || ''" /></template>
    <template #product_type="{ row }">{{
        $t(goodsType[row.product_type])
      }}</template>
    <template #product_stock="{ row }"><span :class="{ danger: row.product_type === 1 && row.is_min_stock }">{{ row.product_type === 1 ? row.product_stock : "--" }}</span></template>
    <!-- <template #status="{row}"><el-tag :type="row.status ? '' : 'danger'">{{$t(statusTxt[row.status])}}</el-tag></template> -->
  </ProTable>

  <!--  -->
  <el-dialog :title="
        $t(`goodsCate.${this.baseForm.product_id ? 'editCate' : 'addCate'}`)
      " :visible.sync="show" :width="device === 'desktop' ? '1100px' : '100%'" :close-on-click-modal="false" @closed="resetForm">
    <el-tabs v-model="activeName">
      <!--  -->
      <el-tab-pane :label="$t('goods.base')" name="base">
        <!-- <ProForm ref="baseForm" :echo="baseForm" :config="EFC" :rules="rules" :msg="$t('goods.noBase')"></ProForm> -->
        <el-form ref="baseForm" :model="baseForm" :rules="rules" label-position="top">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item :label="$t('goods.image')" prop="product_img">
                <BaseFile v-model="baseForm.product_img" :config="{ attr: { limit: 1 } }" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.status')" prop="product_status">
                <el-select v-model="baseForm.product_status" class="f1">
                  <el-option v-for="(v, i) in statusOption" :key="i" :label="$t('goods.' + v)" :value="i*1" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.zh_name')" prop="product_name">
                <el-input v-model="baseForm.product_name" :placeholder="$t('common.enter')" />
              </el-form-item>
            </el-col>
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.en_name')" prop="en_product_name">
                <el-input v-model="baseForm.en_product_name" :placeholder="$t('common.enter')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.zh_syno')" prop="product_synopsis">
                <el-input v-model="baseForm.product_synopsis" :placeholder="$t('common.enter')" />
              </el-form-item>
            </el-col>
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.en_syno')" prop="en_product_synopsis">
                <el-input v-model="baseForm.en_product_synopsis" :placeholder="$t('common.enter')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.type')" prop="product_type">
                <div class="df">
                  <el-select v-model="baseForm.product_type" class="f1">
                    <el-option v-for="(lab, val) in ptOption" :key="val" :label="$t('goods.' + lab)" :value="val * 1" />
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.cate')" prop="product_sort_id">
                <div class="df">
                  <el-select v-model="baseForm.product_sort_id" class="f1">
                    <el-option v-for="(item, index) in psOption" :key="index" :label="item.label" :value="item.value" />
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.barcode')" prop="product_barcode">
                <el-input v-model="baseForm.product_barcode" :placeholder="$t('common.enter')" />
              </el-form-item>
            </el-col>
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.location')" prop="product_location">
                <el-input v-model="baseForm.product_location" :placeholder="$t('common.enter')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.supplier_name')">
                <el-input v-model="baseForm.purchase_supplier" :placeholder="$t('common.enter')" />
              </el-form-item>
            </el-col>
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.supplier_email')">
                <el-input v-model="baseForm.purchase_contact" :placeholder="$t('common.enter')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.price')" prop="product_price">
                <div class="df">
                  <el-input-number v-model="baseForm.product_price" class="f1" :min="0" />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.cost')" prop="product_cost">
                <div class="df">
                  <el-input-number v-model="baseForm.product_cost" class="f1" :min="0" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.stock')" prop="product_stock">
                <div class="df">
                  <!-- 請將產品編輯的庫存量改成禁止修改，只保留在規格中修改庫存量 -->
                  <el-input-number v-model="baseForm.product_stock" class="f1" :min="0" clearable :disabled="baseForm.product_id" />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="device === 'desktop' ? 12 : 24">
              <el-form-item :label="$t('goods.hand')" prop="product_hand">
                <div class="df">
                  <el-input-number v-model="baseForm.product_hand" class="f1" :min="0" clearable />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-button type="primary" @click="activeName = 'detail'">{{
            $t("common.next")
          }}</el-button>
      </el-tab-pane>
      <!--  -->
      <el-tab-pane :label="$t('goods.detail')" name="detail">
        <el-form ref="detailForm" :model="detailForm" label-position="top">
          <el-form-item prop="album">
            <div slot="label" class="df aic">
              <span class="mr10">{{ $t("goods.album") }}</span>
              <el-switch v-model="detailForm.is_album" :active-value="1" :inactive-value="0" />
            </div>
            <BaseFile v-if="detailForm.is_album === 1" v-model="detailForm.album" :config="{ attr: { limit: 10 } }" />
          </el-form-item>
          <el-form-item :label="$t('goods.zh_desc')" prop="product_describe">
            <QuillEditor v-model="detailForm.product_describe" width="1000" />
          </el-form-item>
          <el-form-item :label="$t('goods.en_desc')" prop="en_product_describe">
            <QuillEditor v-model="detailForm.en_product_describe" width="1000" />
          </el-form-item>
          <el-button type="primary" @click="activeName = 'base'">{{
              $t("common.prev")
            }}</el-button>
          <el-button type="primary" @click="activeName = 'else'">{{
              $t("common.next")
            }}</el-button>
        </el-form>
      </el-tab-pane>
      <!--  -->
      <el-tab-pane :label="$t('goods.else')" name="else">
        <el-form ref="elseForm" :model="elseForm" label-position="top">
          <el-form-item>
            <el-checkbox-group v-model="checked">
              <el-checkbox v-for="(item, index) in options" :key="index" :label="item">{{ $t("goods." + item) }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item :label="$t('goods.integral')" prop="integral_num">
            <el-input-number v-model="elseForm.integral_num" :min="0" :disabled="!checked.includes('is_integral')" />
          </el-form-item>
          <el-form-item :label="$t('goods.tag')" prop="tag">
            <el-tag v-for="(item, index) in elseForm.tag" :key="index" closable :disable-transitions="false" @close="delTag(index)">{{
                item[[(language === "en" ? "en_" : "") + "product_tag_name"]]
              }}</el-tag>
            <el-button :disabled="!checked.includes('is_tag')" @click="tagInputVisible = true">+ New Tag</el-button>
          </el-form-item>
          <el-button type="primary" @click="activeName = 'detail'">{{
              $t("common.prev")
            }}</el-button>
          <el-button type="primary" :loading="isLoadSub" @click="submit">{{
              $t("common.confirm")
            }}</el-button>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
  <ProLanginps :show.sync="tagInputVisible" @submit="addTag" />
  <!--  -->
  <el-dialog :title="$t('goods.details')" :visible.sync="showDetails" :width="device === 'desktop' ? '1100px' : '100%'" :close-on-click-modal="false" @closed="details = null">
    <template v-if="details">
      <el-descriptions :title="$t('goods.base')" :column="device === 'desktop' ? 2 : 1" border>
        <template v-for="(lab, key, index) in baseLab">
          <el-descriptions-item v-if="key === 'product_img'" :key="index" :label="$t(lab)">
            <ProImage :src="details.product_img" />
          </el-descriptions-item>
          <el-descriptions-item v-else-if="key === 'product_type'" :key="index" :label="$t(lab)">{{ $t(goodsType[details.product_type]) }}</el-descriptions-item>
          <el-descriptions-item v-else :key="index" :label="$t(lab)">{{
              details[key]
            }}</el-descriptions-item>
        </template>
      </el-descriptions>
      <el-descriptions class="mt40" :title="$t('goods.detail')" :column="1" :direction="device === 'desktop' ? 'horizontal' : 'vertical'" border>
        <el-descriptions-item :label="`${$t('goods.album')}（${$t(
              switchTxts[details.is_album]
            )}）`">
          <ProImage :src="details.product_album.map(({ image_url }) => image_url)" expand />
        </el-descriptions-item>
        <el-descriptions-item :label="$t('goods.zh_desc')">
          <ProPreview :content="details.product_describe" />
        </el-descriptions-item>
        <el-descriptions-item :label="$t('goods.en_desc')">
          <ProPreview :content="details.en_product_describe" />
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions class="mt40" :title="$t('goods.else')" :column="1" border>
        <el-descriptions-item :label="$t('goods.is_priority')">{{
            $t(switchTxts[details.is_priority])
          }}</el-descriptions-item>
        <el-descriptions-item :label="`${$t('goods.integral')}（${$t(
              switchTxts[details.is_integral]
            )}）`">{{ details.integral_num }}</el-descriptions-item>
        <el-descriptions-item :label="`${$t('goods.tag')}（${$t(switchTxts[details.is_tag])}）`">
          <el-tag v-for="(item, index) in details.product_tag" :key="index">{{
            item[(language === "en" ? "en_" : "") + "product_tag_name"]
          }}</el-tag>
        </el-descriptions-item>
        <!-- <el-descriptions-item :label="$t('common.created_at')">{{ details.created_at }}</el-descriptions-item>
          <el-descriptions-item :label="$t('common.updated_at')">{{ details.updated_at }}</el-descriptions-item> -->
      </el-descriptions>
    </template>
  </el-dialog>
  <!--  -->
  <el-dialog :title="$t('goods.specs')" :visible.sync="showSpec" :width="device === 'desktop' ? '1100px' : '100%'" :close-on-click-modal="false" @closed="resetSpec">
    <el-form ref="specForm" v-loading="isLoadSpecForm" :model="specForm" label-position="top">
      <el-form-item :label="$t('goods.isSpecs')" prop="is_specs">
        <el-radio-group v-model="specForm.is_specs">
          <el-radio :label="0" border>{{ $t("goods.sSpec") }}</el-radio>
          <el-radio :label="1" border>{{ $t("goods.mSpec") }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="specForm.is_specs">
        <el-form-item :label="$t('goods.specsCate')" prop="specs_sort_id">
          <el-select v-model="specForm.specs_sort_id" :placeholder="$t('common.selectPh')" clearable>
            <el-option v-for="(item, index) in specOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
          <el-button style="margin-left: 10px" type="primary" :disabled="!specForm.specs_sort_id" @click="sltSpec">{{ $t("common.confirm") }}</el-button>
          <div v-for="(lab, li) in specSlt" :key="li" class="ptb10">
            <div class="lab">
              {{ lab[(language === "en" ? "en_" : "") + "specs_key_name"] }}
            </div>
            <div class="plr10">
              <el-tag v-for="(val, vi) in lab.specs_value" :key="vi" class="mlr10" type="primary">{{
                  val[(language === "en" ? "en_" : "") + "specs_value_name"]
                }}</el-tag>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="skuHead.length && productSku.length" :label="$t('goods.specsSku')">
          <div :class="{ 'tab-spec': device === 'mobile' }">
            <table v-loading="isLoadSku">
              <thead>
                <tr>
                  <th rowspan="1" :colspan="skuHead.length">
                    {{ $t("goods.specs") }}
                  </th>
                  <th>{{ $t("goods.price") }}</th>
                  <th>{{ $t("goods.cost") }}</th>
                  <th>{{ $t("goods.stock") }}</th>
                </tr>
                <tr>
                  <th rowspan="1" :colspan="skuHead.length">
                    {{ $t("goods.batchSet") }}
                  </th>
                  <th rowspan="2">
                    <el-input-number v-model="batchForm.price" :min="0" @change="batchSet($event, 'price')" />
                  </th>
                  <th rowspan="2">
                    <el-input-number v-model="batchForm.cost" :min="0" @change="batchSet($event, 'cost')" />
                  </th>
                  <th rowspan="2">
                    <el-input-number v-model="batchForm.stock" :min="0" :disabled="specStockAbled" @change="batchSet($event, 'stock')" />
                  </th>
                </tr>
                <tr>
                  <th v-for="(item, index) in skuHead" :key="index" class="thd-txt" :title="item.product_specs_key">
                    {{ item.product_specs_key }}
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, ri) in productSku" :key="ri">
                  <td v-for="(col, ci) in row" :key="ci" class="thd-txt" :title="col.product_specs_value">
                    {{ col.product_specs_value }}
                  </td>
                  <td>
                    <el-input-number v-model="specForm.product_relation[ri].price" :min="0" />
                  </td>
                  <td>
                    <el-input-number v-model="specForm.product_relation[ri].cost" :min="0" />
                  </td>
                  <td>
                    <el-input-number v-model="specForm.product_relation[ri].stock" :min="0" :disabled="specStockAbled" />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </el-form-item>
        <div v-if="!skuHead.length && !productSku.length && isLoadSku" v-loading="true" />
      </template>

      <template v-else>
        <el-form-item :label="$t('goods.price')" prop="product_price">
          <el-input-number v-model="specForm.product_price" :min="0" />
        </el-form-item>
        <el-form-item :label="$t('goods.cost')" prop="product_cost">
          <el-input-number v-model="specForm.product_cost" :min="0" />
        </el-form-item>
        <el-form-item :label="$t('goods.stock')" prop="product_stock">
          <el-input-number v-model="specForm.product_stock" :min="0" :disabled="specStockAbled" />
        </el-form-item>
      </template>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showSpec = false">{{
          $t("common.cancel")
        }}</el-button>
      <el-button type="primary" :loading="isLoadSub" @click="specSub">{{
          $t("common.confirm")
        }}</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getGoodsCate,
  getGoodsSpace,
  addGoods,
  editGoods,
  delGoods,
  getSpecsGoods,
  addSpecsGoods,
  editSpecsGoods
} from '@/api'
import { goods } from '@/form'
import paging from '@/mixins/paging'
import BaseFile from '@/components/ProForm/baseFile.vue'
import QuillEditor from '@/components/QuillEditor'
export default {
  name: 'ProductList',
  components: { BaseFile, QuillEditor },
  mixins: [paging],
  data() {
    return {
      SFC: goods.SFC,
      // EFC: goods.EFC,
      activeName: 'base',
      show: false,
      delIds: [],
      column: {
        product_id: 'goods.id',
        product_status: 'goods.status',
        product_img: 'goods.image',
        product_name: 'goods.zh_name',
        en_product_name: 'goods.en_name',
        product_type: 'goods.type',
        product_sort_name: 'goods.cate',
        product_price: 'goods.price',
        product_cost: 'goods.cost',
        product_stock: 'goods.stock'
      },
      goodsType: ['', 'goods.product', 'goods.services'],
      goodsStatus: {
        0: 'goods.forbidden',
        '-1': 'goods.delete',
        1: 'goods.normal'
      },
      product_stock: 0,
      baseForm: {
        product_img: '',
        product_name: '',
        en_product_name: '',
        product_synopsis: '',
        en_product_synopsis: '',
        product_type: '',
        product_sort_id: '',
        product_barcode: '',
        product_location: '',
        purchase_supplier: '',
        purchase_contact: '',
        product_status: 1,
        product_cost: 0,
        product_hand: 0,
        product_price: 0,
        product_stock: 0
      },
      statusOption: {
        0: 'forbidden',
        1: 'normal'
      },
      ptOption: {
        1: 'product',
        2: 'services'
      },
      psOption: [],
      detailForm: {
        is_album: 1,
        album: [],
        product_describe: '',
        en_product_describe: ''
      },
      elseForm: {
        integral_num: '0',
        tag: []
      },
      checked: [],
      options: ['is_integral', 'is_tag', 'is_priority'],
      tagInputVisible: false,
      isLoadSub: false,
      showDetails: false,
      details: null,
      baseLab: {
        product_name: 'goods.zh_name',
        en_product_name: 'goods.en_name',
        product_synopsis: 'goods.zh_syno',
        en_product_synopsis: 'goods.en_syno',
        product_type: 'goods.type',
        product_sort_name: 'goods.cate',
        product_barcode: 'goods.barcode',
        product_location: 'goods.location',
        purchase_supplier: 'goods.supplier_name',
        purchase_contact: 'goods.supplier_email',
        product_price: 'goods.price',
        product_cost: 'goods.cost',
        product_stock: 'goods.stock',
        product_hand: 'goods.hand',
        product_img: 'goods.image'
      },
      switchTxts: ['common.close', 'common.open'],
      showSpec: false,
      isLoadSpecForm: false,
      specForm: {
        is_specs: 0,
        specs_sort_id: '',
        product_price: 0,
        product_cost: 0,
        product_stock: 0,
        product_relation: [],
        product_specs_key: []
      },
      specStockAbled: false,
      goodsSpec: null,
      specOptions: [],
      specData: [],
      specSlt: [],
      isLoadSku: false,
      skuHead: [],
      productSku: [],
      batchForm: {
        price: 0,
        cost: 0,
        stock: 0
      },
      rules: {
        product_img: [
          {
            required: true,
            message: this.$t('common.required'),
            trigger: 'blur'
          }
        ],
        product_name: [
          {
            required: true,
            message: this.$t('common.required'),
            trigger: 'blur'
          }
        ],
        en_product_name: [
          {
            required: true,
            message: this.$t('common.required'),
            trigger: 'blur'
          }
        ],
        product_synopsis: [
          {
            required: true,
            message: this.$t('common.required'),
            trigger: 'blur'
          }
        ],
        en_product_synopsis: [
          {
            required: true,
            message: this.$t('common.required'),
            trigger: 'blur'
          }
        ],
        product_type: [
          {
            required: true,
            message: this.$t('common.required'),
            trigger: 'blur'
          }
        ],
        product_sort_id: [
          {
            required: true,
            message: this.$t('common.required'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.init()
    this.getList('Goods')
  },
  computed: {
    ...mapGetters(['language'])
  },
  watch: {
    'baseForm.product_type'(val) {
      this.baseForm.product_stock = val === 1 ? this.product_stock : 0
    },
    'specForm.specs_sort_id'(val) {
      if (!val) return
      const target = this.specData.find((item) => item.specs_sort_id === val)
      this.specSlt = target.specs_key
    },
    list(val) {
      val.forEach((row) => {
        if (row.product_type === 1 && row.is_min_stock) {
          setTimeout(() => {
            this.$notify({
              type: 'error',
              title: this.$t('goods.minStockErr'),
              message:
                row[(this.language === 'zh' ? '' : 'en_') + 'product_name'],
              position: 'bottom-right'
            })
          })
        }
      })
    }
  },
  methods: {
    // 低庫存提醒
    tableRowClassName({ row }) {
      if (row.product_type === 1 && row.is_min_stock) {
        return 'warning-row'
      }
      return ''
    },
    // 規格組合函數
    cartesianProductOf(args) {
      return args.reduce(
        (total, current) => {
          const ret = []
          total.forEach((a) => {
            current.forEach((b) => {
              ret.push(a.concat([b]))
            })
          })
          return ret
        },
        [[]]
      )
    },
    async init() {
      getGoodsCate().then(({ results }) => {
        const cate = results.map(({ product_sort_id, product_sort_name }) => ({
          label: product_sort_name,
          value: product_sort_id,
          trans: '1'
        }))
        this.$set(this.SFC.formItems[2].item, 'options', cate)
        // this.$set(this.EFC.formItems[3][1].item, 'options', cate)
        this.psOption = cate
      })
      getGoodsSpace().then(({ results }) => {
        this.specOptions = results.map(
          ({ specs_sort_id, specs_sort_name, en_specs_sort_name }) => ({
            value: specs_sort_id,
            label:
              this.language === 'en' ? en_specs_sort_name : specs_sort_name
          })
        )
        this.specData = results
      })
    },
    // 添加標簽
    addTag({ zh: product_tag_name, en: en_product_tag_name }) {
      this.elseForm.tag.push({ product_tag_name, en_product_tag_name })
    },
    // 刪除標簽
    delTag(index) {
      this.elseForm.tag.splice(index, 1)
    },
    // 查看
    view(scope) {
      this.details = this.$lodash.cloneDeep(scope)
      this.details.product_describe =
        this.details.product_describe &&
        this.details.product_describe.replace(
          /<img/g,
          '<img style="width:100%"'
        )
      this.details.en_product_describe =
        this.details.en_product_describe &&
        this.details.en_product_describe.replace(
          /<img/g,
          '<img style="width:100%"'
        )
      this.showDetails = true
    },
    // 批量设置
    batchSet(e, type) {
      this.specForm.product_relation.forEach((item) => (item[type] = e))
    },
    // 規格
    async spec({ product_id, product_type }) {
      this.specStockAbled = product_type === 2
      this.showSpec = true
      try {
        this.isLoadSpecForm = true
        const { results } = await getSpecsGoods({ product_id })
        Object.assign(this.specForm, results)
        if (results.product_specs_key.length) {
          this.specSlt = results.product_specs_key.map(
            ({
              product_specs_key,
              en_product_specs_key,
              product_specs_value
            }) => ({
              specs_key_name: product_specs_key,
              en_specs_key_name: en_product_specs_key,
              specs_value: product_specs_value.map(
                ({ product_specs_value, en_product_specs_value }) => ({
                  specs_value_name: product_specs_value,
                  en_specs_value_name: en_product_specs_value
                })
              )
            })
          )
          this.skuHead = results.product_specs_key.map(
            ({ product_specs_key, product_specs_key_id }) => ({
              product_specs_key,
              product_specs_key_id
            })
          )
          const specVals = results.product_specs_key.map(
            (item) => item.product_specs_value
          )
          this.productSku = this.cartesianProductOf(specVals)
          this.specForm.product_relation = results.product_relation.length
            ? results.product_relation
            : this.productSku.map((item) => ({
              product_specs_value_id: item
                .map(({ product_specs_value_id }) => product_specs_value_id)
                .join('-'),
              product_relation_id: '',
              price: 0,
              cost: 0,
              stock: 0
            }))
        }
      } catch (error) {
      } finally {
        this.isLoadSpecForm = false
      }
    },
    // 規格模板選擇
    async sltSpec() {
      const result = await this.$confirm(
        this.$t('goods.tips3'),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
          center: this.device === 'mobile',
          customClass: this.device === 'mobile' ? 'mmw' : ''
        }
      ).catch((e) => e)
      if (result === 'cancel') return
      const val = this.specForm.specs_sort_id
      const target = this.specData.find((item) => item.specs_sort_id === val)
      const specs_key = target.specs_key.map(
        ({ specs_key_name, en_specs_key_name, specs_value }) => ({
          product_specs_key: specs_key_name,
          en_product_specs_key: en_specs_key_name,
          specs_value: specs_value.map(
            ({ specs_value_name, en_specs_value_name }) => ({
              product_specs_value: specs_value_name,
              en_product_specs_value: en_specs_value_name
            })
          )
        })
      )

      try {
        this.isLoadSku = true
        const { results } = await addSpecsGoods({
          product_id: this.specForm.product_id,
          specs_key
        })
        this.skuHead = results.map(
          ({ product_specs_key, product_specs_key_id }) => ({
            product_specs_key,
            product_specs_key_id
          })
        )
        const specVals = results.map((item) => item.product_specs_value)
        this.productSku = this.cartesianProductOf(specVals)
        this.specForm.product_relation = this.productSku.map((item) => ({
          product_specs_value_id: item
            .map(({ product_specs_value_id }) => product_specs_value_id)
            .join('-'),
          product_relation_id: '',
          price: 0,
          cost: 0,
          stock: 0
        }))
      } catch (error) {
      } finally {
        this.isLoadSku = false
      }
    },
    // 重置規格表單
    resetSpec() {
      this.specForm = {
        is_specs: 0,
        specs_sort_id: '',
        product_price: 0,
        product_cost: 0,
        product_stock: 0,
        product_relation: [],
        product_specs_key: []
      }
      this.batchForm = { price: 0, cost: 0, stock: 0 }
      this.specSlt = []
      this.skuHead = []
      this.productSku = []
    },
    // 提交規格商品
    async specSub() {
      const {
        product_id,
        is_specs,
        product_price,
        product_cost,
        product_stock,
        product_relation
      } = this.specForm
      if (is_specs) {
        if (!product_relation.length) {
          return this.$message({
            message: this.$t('goods.tips1'),
            type: 'warning'
          })
        }
        if (this.specStockAbled) {
          if (product_relation.some((item) => !item.price || !item.cost)) {
            return this.$message({
              message: this.$t('goods.tips5'),
              type: 'warning'
            })
          }
        } else {
          if (
            product_relation.some(
              (item) => !item.price || !item.cost || !item.stock
            )
          ) {
            return this.$message({
              message: this.$t('goods.tips2'),
              type: 'warning'
            })
          }
        }
      } else {
        if (this.specStockAbled) {
          if ([product_price, product_cost].includes(0)) {
            return this.$message({
              message: this.$t('goods.tips5'),
              type: 'warning'
            })
          }
        } else {
          if ([product_price, product_cost, product_stock].includes(0)) {
            return this.$message({
              message: this.$t('goods.tips2'),
              type: 'warning'
            })
          }
        }
      }

      try {
        this.isLoadSub = true
        await editSpecsGoods({
          product_id,
          is_specs,
          product_price,
          product_cost,
          product_stock,
          product_relation
        })
        this.$message({ message: this.$t('common.success'), type: 'success' })
        this.showSpec = false
        this.getList('Goods')
      } catch (error) {
      } finally {
        this.isLoadSub = false
      }
    },
    // 編輯
    edit({
      product_id,
      en_product_name,
      en_product_synopsis,
      product_barcode,
      product_cost,
      product_hand,
      product_img,
      product_location,
      purchase_supplier,
      purchase_contact,
      product_name,
      product_price,
      product_status,
      product_sort_id,
      product_stock,
      product_synopsis,
      product_type,
      is_album,
      product_album,
      product_describe,
      en_product_describe,
      is_priority,
      is_integral,
      is_tag,
      integral_num,
      product_tag
    }) {
      const album = product_album.map(({ image_url }) => image_url)
      const tag = product_tag.map(
        ({ product_tag_name, en_product_tag_name }) => ({
          product_tag_name,
          en_product_tag_name
        })
      )
      this.product_stock = product_stock
      this.baseForm = {
        product_id,
        en_product_name,
        en_product_synopsis,
        product_barcode,
        product_cost,
        product_hand,
        product_img,
        purchase_supplier,
        purchase_contact,
        product_location,
        product_name,
        product_price,
        product_sort_id,
        product_stock,
        product_synopsis,
        product_type,
        product_status
      }
      this.detailForm = {
        is_album,
        album,
        product_describe,
        en_product_describe
      }
      const iss = { is_priority, is_integral, is_tag }
      for (const i in iss) {
        if (iss[i] === 1) {
          this.checked.push(i)
        }
      }
      this.elseForm = { integral_num, tag }
      this.show = true
    },
    // 批量刪除
    async del({ product_id } = {}) {
      this.asyncMsg(async(instance, done) => {
        instance.confirmButtonLoading = true
        try {
          await delGoods({
            product_id: product_id ? [product_id] : this.delIds
          })
          if (product_id) {
            this.list = this.list.filter(
              (item) => item.product_id !== product_id
            )
            this.page.total--
          } else {
            this.list = this.list.filter(
              (item) => !this.delIds.includes(item.product_id)
            )
            this.page.total -= this.delIds.length
          }
          this.delIds = []
          done()
        } catch (error) {
        } finally {
          instance.confirmButtonLoading = false
        }
      })
    },
    // 操作
    onRcc({ scope: { row }, type }) {
      this[type](row)
    },
    // 重置產品表單
    resetForm() {
      this.activeName = 'base'
      this.$refs.baseForm.resetFields()
      this.$refs.detailForm.resetFields()
      this.$refs.elseForm.resetFields()
      this.product_stock = 0
      this.baseForm = {
        product_img: '',
        product_name: '',
        en_product_name: '',
        product_synopsis: '',
        en_product_synopsis: '',
        product_type: '',
        product_sort_id: '',
        product_barcode: '',
        product_location: '',
        purchase_supplier: '',
        purchase_contact: '',
        product_cost: 0,
        product_hand: 0,
        product_price: 0,
        product_stock: 0
      }
      this.detailForm = {
        is_album: 1,
        album: [],
        product_describe: '',
        en_product_describe: ''
      }
      this.elseForm = { integral_num: '0', tag: [] }
      this.checked = []
    },
    // 提交產品表單
    submit() {
      this.$refs.baseForm.validate(async(valid) => {
        if (!valid) {
          return this.$message({
            message: this.$t('goods.noBase'),
            type: 'warning'
          })
        }
        const { product_type, product_price, product_cost, product_stock } =
          this.baseForm
        if (product_type === 1 && [product_price, product_cost].includes(0)) {
          return this.$message({
            message: this.$t('goods.tips2'),
            type: 'warning'
          })
        }
        if (product_type === 2 && [product_price, product_cost].includes(0)) {
          return this.$message({
            message: this.$t('goods.tips5'),
            type: 'warning'
          })
        }
        if (this.detailForm.is_album && !this.detailForm.album.length) {
          return this.$message({
            message: this.$t('goods.noAlbum'),
            type: 'warning'
          })
        }
        if (
          this.checked.includes('is_integral') &&
          this.elseForm.integral_num == 0
        ) {
          return this.$message({
            message: this.$t('goods.noInt'),
            type: 'warning'
          })
        }
        if (this.checked.includes('is_tag') && !this.elseForm.tag.length) {
          return this.$message({
            message: this.$t('goods.noTag'),
            type: 'warning'
          })
        }

        const iss = {}
        this.options.forEach((item) => {
          iss[item] = this.checked.includes(item) ? 1 : 0
        })

        try {
          this.isLoadSub = true
          const params = Object.assign(
            {},
            this.baseForm,
            this.detailForm,
            this.elseForm,
            iss
          )
          if (params.product_id) {
            await editGoods(params)
          } else {
            await addGoods(params)
          }
          this.$message({
            message: this.$t('common.success'),
            type: 'success'
          })
          this.show = false
          this.getList('Goods')
        } catch (error) {
          console.log(error)
        } finally {
          this.isLoadSub = false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.danger {
  color: #f56c6c;
}
.el-tag {
  margin-right: 10px;
}

.lab {
  margin-bottom: 10px;
  font-size: 12px;
  font-weight: bold;
}

table,
th,
td {
  border: 1px solid #dddddd;
  border-collapse: collapse;
}
th,
td {
  padding: 5px 20px;
}
.thd-txt {
  max-width: 120px;
  word-break: keep-all;
  text-overflow: ellipsis;
  overflow: hidden;
  box-sizing: border-box;
}
.tab-spec {
  width: 100%;
  overflow-y: scroll;
}
</style>

<style>
.el-notification__content {
  word-break: break-all;
}
</style>
